function setupWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}

var u = navigator.userAgent;
if (u.indexOf('iPhone') > -1) {//苹果手机
    setupWebViewJavascriptBridge(function(bridge) {
        bridge.registerHandler('testJSFunction', function(data, responseCallback) {
            //alert('JS方法被调用:'+data);
            responseCallback('js执行过了');
        })
    })
}

var tok='';

function getTokenI() {
    WebViewJavascriptBridge.callHandler('getToken', {'foo': 'bar'}, function(response) {
        //alert('扫描结果:' + response);
        tok=response;
        return response
    })
}
var userId='';
function getUserIdI() {
    WebViewJavascriptBridge.callHandler('getUserId', {'foo': 'bar'}, function(response) {
        //alert('扫描结果:' + response);
        userId=response;
        return response
    })
}

function callNumberI(photo) {
    var params = photo;
    WebViewJavascriptBridge.callHandler('callNumber',params,function(response) {
        //alert('photo:' + response);
        return response
    });
}


window.onload=function(){



};

var webData=[
    {
        "userName": "仓储部员工1",
        "role": [
            "仓储部员工"
        ],
        "mobile": "13700000000"
    },
    {
        "userName": "维修主管2",
        "role": [
            "维修部主管"
        ],
        "mobile": "13711111111"
    },
    {
        "userName": "财务主管",
        "role": [
            "财务部主管"
        ],
        "mobile": "13722222222"
    },
    {
        "userName": "生产部主管",
        "role": [
            "生产部主管"
        ],
        "mobile": "13733333333"
    },
    {
        "userName": "采购部主管",
        "role": [
            "采购部主管"
        ],
        "mobile": "13744444444"
    },
    {
        "userName": "仓储部主管",
        "role": [
            "仓储部主管",
            "维修部主管"
        ],
        "mobile": "13755555555"
    },
    {
        "userName": "财务部员工",
        "role": [
            "财务部员工"
        ],
        "mobile": "13766666666"
    },{
        "userName": "q财务部员工",
        "role": [
            "财务部员工"
        ],
        "mobile": "13766666666"
    },
    {
        "userName": "生产部员工",
        "role": [
            "生产部员工"
        ],
        "mobile": "13777777777"
    },
    {
        "userName": "p维修部员工",
        "role": [
            "维修部员工"
        ],
        "mobile": "13788888888"
    },
    {
        "userName": "采购部员工",
        "role": [
            "采购部员工"
        ],
        "mobile": "13799999999"
    },{
        "userName": "p采购部员工",
        "role": [
            "采购部员工"
        ],
        "mobile": "13799999999"
    },{
        "userName": "采购部员工",
        "role": [
            "采购部员工"
        ],
        "mobile": "13799999999"
    },
    {
        "userName": "i测试",
        "role": [
            "超级管理员"
        ],
        "mobile": "17688702605"
    },
    {
        "userName": "j测试",
        "role": [
            "超级管理员"
        ],
        "mobile": "17688702605"
    },
    {
        "userName": "w测试",
        "role": [
            "超级管理员"
        ],
        "mobile": "17688702605"
    },
    {
        "userName": "e测试",
        "role": [
            "超级管理员"
        ],
        "mobile": "17688702605"
    },
    {
        "userName": "e测试",
        "role": [
            "超级管理员"
        ],
        "mobile": "17688702605"
    }
]




/*
* 数据排序
* */
var lochData={
    'top':[],
    'a':[],
    'b':[],
    'c':[],
    'd':[],
    'e':[],
    'f':[],
    'g':[],
    'h':[],
    'i':[],
    'j':[],
    'k':[],
    'l':[],
    'm':[],
    'n':[],
    'o':[],
    'p':[],
    'q':[],
    'r':[],
    's':[],
    't':[],
    'u':[],
    'v':[],
    'w':[],
    'x':[],
    'y':[],
    'z':[],
    'zz':[],
}
function ToWebData(webData,topData) {
    for(var j=0;j<topData.length;j++){
        if(j<3){
            lochData.top.push(topData[j]);
        }
    }
    for(var i=0;i<webData.length;i++){
        var letter=makePy(webData[i].userName.charAt(0))[0].toUpperCase();
        switch(letter){
            case "A":
                lochData.a.push(webData[i]);
                break;
            case "B":
                lochData.b.push(webData[i]);
                break;
            case "C":
                lochData.c.push(webData[i]);
                break;
            case "D":
                lochData.d.push(webData[i]);
                break;
            case "E":
                lochData.e.push(webData[i]);
                break;
            case "F":
                lochData.f.push(webData[i]);
                break;
            case "G":
                lochData.g.push(webData[i]);
                break;
            case "H":
                lochData.h.push(webData[i]);
                break;
            case "I":
                lochData.i.push(webData[i]);
                break;
            case "J":
                lochData.j.push(webData[i]);
                break;
            case "K":
                lochData.k.push(webData[i]);
                break;
            case "L":
                lochData.l.push(webData[i]);
                break;
            case "M":
                lochData.m.push(webData[i]);
                break;
            case "N":
                lochData.n.push(webData[i]);
                break;
            case "O":
                lochData.o.push(webData[i]);
                break;
            case "P":
                lochData.p.push(webData[i]);
                break;
            case "Q":
                lochData.q.push(webData[i]);
                break;
            case "R":
                lochData.r.push(webData[i]);
                break;
            case "S":
                lochData.s.push(webData[i]);
                break;
            case "T":
                lochData.t.push(webData[i]);
                break;
            case "U":
                lochData.u.push(webData[i]);
                break;
            case "V":
                lochData.v.push(webData[i]);
                break;
            case "W":
                lochData.w.push(webData[i]);
                break;
            case "X":
                lochData.x.push(webData[i]);
                break;
            case "Y":
                lochData.y.push(webData[i]);
                break;
            case "Z":
                lochData.z.push(webData[i]);
                break;
            default:
                lochData.zz.push(webData[i]);
                break;
        }
    }

    return lochData;

}


/*
* 生成HTML
* */
function htmlData(lochData) {
    var htmlVal='<div class="contacts-header"></div> <ul class="contacts-content">';
    var htmlNav='';
    var arrNav=new Array();
    for(var id in lochData) {
        var id=id;
        if(lochData[id].length>0){
            var navId='';
            if(id=='zz'){
                navId='#'
            }else if(id=='top'){
                navId='置顶';
            }else{
                navId=id;
            }
            arrNav.push(navId);
            htmlVal+='<li id="'+navId+'" class="contacts-group">'+
                '<div class="contacts-group-hd">'+navId+'</div>'+
                '<div class="contacts-group-bd">';
            for(var i=0;i<lochData[id].length;i++){
                htmlVal+='<div class="bottom"></div><div class="li"><div class="libox" id="libox">'+
                    '<p><span class="title">姓名：</span><span class="userName">'+lochData[id][i].userName+'</span></p>';
                if(lochData[id][i].user_position!=undefined){
                    htmlVal+='<p><span class="title">岗位：</span><span class="roleName">'+lochData[id][i].user_position+'</span></p>';
                }
                /*for(var j=0;j<lochData[id][i].role.length;j++){
                    htmlVal+='<p><span class="title">角色：</span><span class="roleName">'+lochData[id][i].role[j]+'</span></p>';
                }*/
                htmlVal+='<p><span class="title">电话：</span><span class="photo">'+lochData[id][i].mobile+'</span></p>';
                if(lochData[id][i].cornet!=undefined){
                    htmlVal+='<p><span class="title">短号：</span><span class="photo photoS">'+lochData[id][i].cornet+'</span></p>';
                }
                if(id=='top'){
                    htmlVal+='<img class="photoimg" src="img/phtoto.png">'+
                        '</div><div class="lipro" onclick="noTop(this,'+lochData[id][i].mobile+')">取消置顶</div></div>';
                }else{
                    htmlVal+='<img class="photoimg" src="img/phtoto.png">'+
                        '</div><div class="lipro" onclick="setTop(this,'+lochData[id][i].mobile+')">置顶</div></div>';
                }

            }
            htmlVal+='<div class="bottom"></div></div>'+
                '</li>';
        }
    }
    if(arrNav.length>0){
        var htmlNav='';
        for(var i=0;i<arrNav.length;i++){
            htmlNav+='<li alt="'+arrNav[i]+'">'+arrNav[i]+'</li>'
        }
        htmlVal+='</ul> <ul class="contacts-nav" id="contacts-nav">'+htmlNav+'</ul>';
        $('.contacts-bd').html(htmlVal)
    }else{
        $('.contacts-bd').html('<div style="text-align: center;font-size: 0.35rem;color: #888888;">暂无数据！</div>')
    }

    setTimeout(function () {
        $('.contacts').ublue_ContactsList();
        //滑动事件
        touch()
    },200)

}


/*
 * 条件数据排序
 * */
function IflochDataFn(ifData) {
    var IflochData={
        'a':[],
        'b':[],
        'c':[],
        'd':[],
        'e':[],
        'f':[],
        'g':[],
        'h':[],
        'i':[],
        'j':[],
        'k':[],
        'l':[],
        'm':[],
        'n':[],
        'o':[],
        'p':[],
        'q':[],
        'r':[],
        's':[],
        't':[],
        'u':[],
        'v':[],
        'w':[],
        'x':[],
        'y':[],
        'z':[],
        'zz':[],
    }
    for(var id in lochData) {
        var id=id;
        if(id!='top'){
            if(lochData[id].length>0){
                for(var i=0;i<lochData[id].length;i++){
                    if(lochData[id][i].userName.indexOf(ifData)>=0){
                        var letter=makePy(lochData[id][i].userName.charAt(0))[0].toUpperCase();
                        switch(letter){
                            case "A":
                                IflochData.a.push(lochData[id][i]);
                                break;
                            case "B":
                                IflochData.b.push(lochData[id][i]);
                                break;
                            case "C":
                                IflochData.c.push(lochData[id][i]);
                                break;
                            case "D":
                                IflochData.d.push(lochData[id][i]);
                                break;
                            case "E":
                                IflochData.e.push(lochData[id][i]);
                                break;
                            case "F":
                                IflochData.f.push(lochData[id][i]);
                                break;
                            case "G":
                                IflochData.g.push(lochData[id][i]);
                                break;
                            case "H":
                                IflochData.h.push(lochData[id][i]);
                                break;
                            case "I":
                                IflochData.i.push(lochData[id][i]);
                                break;
                            case "J":
                                IflochData.j.push(lochData[id][i]);
                                break;
                            case "K":
                                IflochData.k.push(lochData[id][i]);
                                break;
                            case "L":
                                IflochData.l.push(lochData[id][i]);
                                break;
                            case "M":
                                IflochData.m.push(lochData[id][i]);
                                break;
                            case "N":
                                IflochData.n.push(lochData[id][i]);
                                break;
                            case "O":
                                IflochData.o.push(lochData[id][i]);
                                break;
                            case "P":
                                IflochData.p.push(lochData[id][i]);
                                break;
                            case "Q":
                                IflochData.q.push(lochData[id][i]);
                                break;
                            case "R":
                                IflochData.r.push(lochData[id][i]);
                                break;
                            case "S":
                                IflochData.s.push(lochData[id][i]);
                                break;
                            case "T":
                                IflochData.t.push(lochData[id][i]);
                                break;
                            case "U":
                                IflochData.a.push(lochData[id][i]);
                                break;
                            case "V":
                                IflochData.v.push(lochData[id][i]);
                                break;
                            case "W":
                                IflochData.w.push(lochData[id][i]);
                                break;
                            case "X":
                                IflochData.x.push(lochData[id][i]);
                                break;
                            case "Y":
                                IflochData.y.push(lochData[id][i]);
                                break;
                            case "Z":
                                IflochData.z.push(lochData[id][i]);
                                break;
                            default:
                                IflochData.zz.push(lochData[id][i]);
                                break;
                        }
                    }
                }

            }
        }
    }
    return IflochData;

}




//输入框事件 onpropertychange oninput
var search=false;   //关键字搜索时，是否刷新列表 true刷新  false不刷新
function searchIn(e){
    var inVal=$('#searchIn').val();
    if(inVal.length==0){   //没有输入搜索内容
        search=false;
        htmlData(lochData)
    }else{
        search=true;
        htmlData(IflochDataFn(inVal));
    }
};


var createNonceStr = function () {
    return Math.random().toString(36).substr(2, 8);
};

var createTimestamp = function () {
    //return parseInt(new Date().getTime() / 1000) + '';
    return parseInt(new Date().getTime());
};

var keyCon="cad7abdb1a070422";
//解密
function Decrypt(word){
    var key = CryptoJS.enc.Utf8.parse(keyCon);
    var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
//加密
function Encrypt(word){
    var key = CryptoJS.enc.Utf8.parse(keyCon);
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
    return encrypted.toString();
}
/*
*
* */
function getData(token,useId) {
    //alert('获得token '+token+'  获得userId '+useId);
    var url='/address/findAll';
    var sequence=createTimestamp();
    var nonceStr=createNonceStr();
    var sign=md5(keyCon+sequence+nonceStr+useId+url+token).toUpperCase();
    var appVersion='2.0.0',osPlatform='H5',osVersion='';
    $.ajax({
        type: "GET",
        dataType: "JSON",
        timeout : 5000,
        url: 'http://mesapitest.51cjgc.com/api/address/findAll',
        //url: 'http://mesapitest.51cjgc.com/api/address/findAll',
        //url: 'http://120.25.195.170:8880/api/address/findAll',
        //url: 'https://saas.51cjgc.com/api/address/findAll',
        beforeSend: function(request) {
            //request.setRequestHeader("Content-Type", "application/json");
            request.setRequestHeader("sequence", sequence);
            request.setRequestHeader("nonceStr", nonceStr);
            request.setRequestHeader("userId", useId);
            request.setRequestHeader("token", token);
            request.setRequestHeader("versionType", "1");
            request.setRequestHeader("osPlatform", osPlatform);
            request.setRequestHeader("appVersion", appVersion);
            request.setRequestHeader("sign", sign);
        },
        success: function (data) {
            console.log(data)
            if(data.code==100){
                //htmlData(ToWebData(webData));
                if(data.content.length>0){
                    webData=data.content;
                    htmlData(ToWebData(data.content,data.content));
                    document.getElementById("spinner").style.display="none";
                    document.getElementById("contacts").style.display="block";
                }else {
                    layer.open({
                        content: '暂无数据'
                        ,btn: '确定'
                    });
                }
                //alert('数据获取成功');
            }else if(data.code==-100){
                if(userAge=='a'){
                    //new jsonStr().alert({content:'您没有权限'})
                    layer.open({
                        content: '您没有权限'
                        ,btn: '确定'
                    });
                }else {
                    layer.open({
                        content: '您没有权限'
                        ,btn: '确定'
                    });
                }
            }else{
                fundebug.notify("address/findAll接口返回数据", JSON.stringify(data));
                //new jsonStr().alert({content:'数据故障，请稍后再试！'})
                layer.open({
                    content: data.message
                    ,btn: '确定'
                });

            }
        },
        error: function(data) {
            if(userAge=='a'){
                //new jsonStr().alert({content:'服务器出错，请稍后再试！'})
                layer.open({
                    content: '服务器出错，请稍后再试！'
                    ,btn: '确定'
                });
            }else {
                layer.open({
                    content: '服务器出错，请稍后再试！'
                    ,btn: '确定'
                });
            }
        }
    });
}

var userAge='';
function jsonStr() {
    this.cfg={
        "title": "提示",
        "content": "",
        "confirm": "确认",
        "cancel": "取消"
    }
}
jsonStr.prototype={
    alert:function (cfg) {
        var CFG = $.extend(this.cfg,cfg);
        var str=JSON.stringify(CFG);
        alert(str);
    }
}

/* 安卓手机 */
function getToken() {
    var str=jsObj.getToken();
    return str
}
function getUserId() {
    var str=jsObj.getUserId();
    return str
}
function callNumber(photo) {
    var str='';
    try{
        str=jsObj.callNumber(photo);
    }catch(e){
        str='调用失败'
    }
    //new jsonStr().alert({content:str})

}

function getDataAnd() {
    //alert('切换公司')
    userAge='a'
    getData(getToken(),getUserId());
    //getData('6f065ed33e4b37031ade16ee9638adcd','1293');
}
function getDataIos() {
    userAge='i';
    setTimeout(function () {
        getTokenI();
        getUserIdI();
    },50)
    setTimeout(function () {
        if(tok!=''){
            getData(tok,userId);
        }
        //getData('6f065ed33e4b37031ade16ee9638adcd','1293');
    },100)
}


$(document).ready(function(){
    var u = navigator.userAgent;
    if (u.indexOf('iPhone') > -1) {//苹果手机
        getDataIos();
    }else if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1){ //alert("安卓手机");
        getDataAnd();
    }else{ //其它;
        getData('6f065ed33e4b37031ade16ee9638adcd','1293');
    }

    $('.contacts-bd').on('click','.photo',function () {
        var photoVal=$(this).html();

        if(userAge=='a'){
            callNumber(photoVal);
        }else if(userAge=='i'){
            callNumberI(photoVal)
        }else{
            alert(photoVal);
        }
    })
    $('.contacts-bd').on('click','.photoimg',function () {
        var photoVal=$(this).parent('.libox').find('.photoS').html()
        if(userAge=='a'){
            callNumber(photoVal);
        }else if(userAge=='i'){
            callNumberI(photoVal)
        }else{
            alert(photoVal);
        }
    })

});

var scroll='';

//取消置顶
function noTop(e,id) {

    var id=id.toString();
    for(var i=0;i<lochData.top.length;i++){
        if(lochData.top[i].mobile==id){
            //滚动条位置
            if($('.contacts-content').scrollTop()>$('.li').height()){
                scroll=$('.contacts-content').scrollTop()+$('.li').height();
            }else{
                scroll=$('.contacts-content').scrollTop();
            }
            lochData.top.splice(i, 1);
            $('.libox').css('left','0');
            //alert('取消成功')
            layer.open({
                content: '取消成功'
                ,btn: '确定'
            });

            //是否刷新列表
            if(!search) {
                htmlData(lochData)
                setTimeout(function () {
                    //设置滚动条位置
                    $('.contacts-content').scrollTop(scroll);
                }, 210)
            }
        }
    }

}
function setTop(e,id) {
    console.log($('.contacts-content').scrollTop())
    var id=id.toString();
    for(var i=0;i<webData.length;i++){
        if(webData[i].mobile==id){
            var idStr=true;
            for(var j=0;j<lochData.top.length;j++){
                if(lochData.top[j].mobile==id){
                    idStr=false;
                    $('.libox').css('left','0');
                    //alert('已置顶')
                    layer.open({
                        content: '已置顶'
                        ,btn: '确定'
                    });
                }
            }
            if(idStr){
                //滚动条位置
                if($('.contacts-content').scrollTop()>$('.li').height()){
                    scroll=$('.contacts-content').scrollTop()+$('.li').height();
                }else{
                    scroll=$('.contacts-content').scrollTop();
                }
                lochData.top.push(webData[i]);
                $('.libox').css('left','0');
                //alert('置顶成功')
                layer.open({
                    content: '置顶成功'
                    ,btn: '确定'
                });


                //是否刷新列表
                if(!search) {
                    htmlData(lochData)
                    setTimeout(function () {
                        //设置滚动条位置
                        $('.contacts-content').scrollTop(scroll);
                    }, 210)
                }

            }
        }
    }
}

//返回角度
function GetSlideAngle(dx, dy) {
    return Math.atan2(dy, dx) * 180 / Math.PI;
}

//根据起点和终点返回方向 1：向上，2：向下，3：向左，4：向右,0：未滑动
function GetSlideDirection(startX, startY, endX, endY) {
    var dy = startY - endY;
    var dx = endX - startX;
    var result = 0;

    //如果滑动距离太短
    if (Math.abs(dx) < 2 && Math.abs(dy) < 2) {
        return result;
    }

    var angle = GetSlideAngle(dx, dy);
    if (angle >= -45 && angle < 45) {
        result = 4;
    } else if (angle >= 45 && angle < 135) {
        result = 1;
    } else if (angle >= -135 && angle < -45) {
        result = 2;
    }
    else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
        result = 3;
    }

    return result;
}

//滑动处理
var startX, startY;

//添加滑动事件
function touch() {
    $('.libox').each(function () {
        var event=$(this)[0];
        if(!$(event).hasClass('touch')){
            $(event).addClass('touch')
            event.addEventListener('touchstart', function (ev) {
                startX = ev.touches[0].pageX;
                startY = ev.touches[0].pageY;
            }, false);
            event.addEventListener('touchend', function (ev) {
                $('.libox').css('left','0');
                var _this=$(this)[0];
                var endX, endY;
                endX = ev.changedTouches[0].pageX;
                endY = ev.changedTouches[0].pageY;
                var direction = GetSlideDirection(startX, startY, endX, endY);
                switch (direction) {
                    case 0:
                        //alert("没滑动");
                        break;
                    case 1:
                        //alert("向上");
                        break;
                    case 2:
                        //alert("向下");
                        break;
                    case 3:
                        //alert("向左");
                        $(_this).css('left','-30%');
                        break;
                    case 4:
                        //alert("向右");
                        $(_this).css('left','0');
                        break;
                    default:
                }
            }, false);
        }
    })
}









